//
//  NetworkingTools.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/10.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit
import AFNetworking
enum RequestType: Int {
    case GET
    case POST
}
class NetworkingTools: AFHTTPSessionManager {
    static let sharedTools: NetworkingTools = {
        let tools = NetworkingTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    func request(type: RequestType,url: String, params: AnyObject?, callBack:(resquest: AnyObject?,error: NSError?) -> ()) {
        if type == .GET {
           GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            print(response)
            callBack(resquest: response, error: nil)
            }, failure: { (_, error) -> Void in
                callBack(resquest: nil, error: error)
           })
            
            
        } else {
            //post请求
            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(resquest: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(resquest: nil, error: error)
            })
        }
    }
    
}

//OAuth 相关借口
extension NetworkingTools {
    //通过授权码（code）获取accesstoken
    func requestAccesstoken(code: String, callBack:(resquest: AnyObject?,error: NSError?) -> ()){
        //准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id" : weiboAPPKey,
            "client_secret" : weiboAPPSecret,
            "grant_type": "authorization_code",
            "code" : code,
            "redirect_uri" : weiboRedirect_Uri
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
    }
    //获取用户信息
    func requestUserInfo(userAccount: UserAccountModel, callBack: (resquest: AnyObject?,error: NSError?) -> ()){
        let url = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        request(.GET, url: url, params: params, callBack: callBack)
    }
    
  
}
//微博网络相关接口
extension NetworkingTools{
    func loadStatues(maxId: Int64 = 0, sinceId: Int64 = 0, callBack:(response: AnyObject?, error: NSError?)->()) {
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params = [
            "access_token" : UserAccountViewModel.sharedUserAccountViewModel.accessToken!,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        request(.GET, url: url, params: params, callBack: callBack)

    
    }
    
}



